import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import { ListView, PullToRefresh, ActivityIndicator } from 'antd-mobile';
import { asyncGetListAction, asyncDeleteListAction, setScrollerPositionAction } from '../../store/actions/news/listAction';
import UIUtil from '../../core/utils/UIUtil';
import EmptyView from '../../views/common/EmptyView';

class NewsListView extends PureComponent
{
    constructor(props)
    {
        super(props);

        this.renderFooter = this.renderFooter.bind(this);
        
        const dataSource = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
            sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
        });

        this.state = {
            dataSource: dataSource.cloneWithRows(this.props.dataList ? this.props.dataList : []),
        };
    }
    componentDidMount()
    {
        this.renderRow = this.renderRow.bind(this);
        this.onRefresh = this.onRefresh.bind(this);
        this.loadNextPage = this.loadNextPage.bind(this);

        // 处理返回
        if(!this.props.dataList)
        {
            this.loadData(this.props.idKey);
        }
        if(this.listView && !isNaN(this.props.listViewOffset))
        {
            this.listView.scrollTo(0, this.props.listViewOffset);
        }
    }
    componentDidUpdate(prevProps, prevState, snapshot)
    {
        if(this.props.dataList !== prevProps.dataList)
        {
            this.setState({dataSource: this.state.dataSource.cloneWithRows(this.props.dataList ? this.props.dataList : [])});
        }
    }
    render()
    {
        return (
            <div className="scenicListBox" style={{height: this.props.height}}>
                {
                    this.renderListView()
                }
                {
                    !this.props.isFetching && (!this.props.dataList || this.props.dataList.length === 0)
                        ?
                        <EmptyView style={{height: this.props.height}} onClick={this.onRefresh}/>
                        :
                        null
                }
                {
                    (this.props.isFetching && this.props.pageIndex === 1)
                        ?
                        <ActivityIndicator 
                            toast
                            text="Loading..." />
                        :null
                }
                <style jsx>{`
                    .scenicListBox{
                        transform: translateZ(0);
                    }
                `}</style>
            </div>
        );
    }
    renderListView()
    {
        if(this.props.dataList && this.props.dataList.length > 0)
        {
            const separator = (sectionID, rowID) => (
                <div
                    key={`${sectionID}-${rowID}`}
                    style={{
                        height: 1,
                        borderBottom: '0.5px solid #dddddd',
                    }}
                />
            );
    
            return (
                <ListView
                    ref={el => {
                        this.listView = el;
                        UIUtil.fixListViewHeightIssue(el, this.props.height);
                    }}
                    dataSource={this.state.dataSource}
                    renderRow={this.renderRow}
                    renderSeparator={separator}
                    style={{
                        height: this.props.height,
                        overflow: 'auto',
                    }}
                    pullToRefresh={<PullToRefresh
                        refreshing={this.props.isFetching}
                        onRefresh={this.onRefresh}
                    />}
                    onEndReached={this.loadNextPage}
                    renderFooter={this.renderFooter}
                    initialListSize={this.props.dataList.length}
                    pageSize={20}
                    scrollRenderAheadDistance={500}
                    scrollEventThrottle={50}
                    onEndReachedThreshold={20}/>
            );
        }
    }
    isEmptyString(str)
    {
        return !str || str.length === 0;
    }
    onRefresh()
    {
        this.props.dispatch(asyncDeleteListAction(this.props.idKey)).then(()=>{
            this.loadData();
        });
    }
    loadNextPage()
    {
        this.loadData();
    }
    renderFooter()
    {
        if(!this.props.isFetching || this.props.hasMore !== true)
        {
            return null;
        }
        return (
            <div className="loadingMore">
                <ActivityIndicator
                    text="Loading..."
                />
            </div>
        );
    }
    renderRow(item, sectionID, rowID)
    {
        let imgUrl = item.F_MiddleImage;
        let date = item.CreateDate;
        date = date ? (date.split(' ')[0]) : date;
        return (
            <div key={rowID} 
                className="newsListItem"
                onClick={()=>{
                    if(this.props.onItemClick)
                    {
                        this.props.onItemClick(item);
                    }
                }}>
                <div style={{backgroundImage: `url(${imgUrl})`}} className="scenicListItemImg"/>
                <div className="newsListItemTextBox">
                    <div className="scenicListItemName">{item.Head}</div>
                    <div className="newsListSecondRow">
                        <img className="newsListIcon" src={require('../../assets/images/time.png')} alt=''/>
                        <div className="newsListItemOthers">{date}</div>
                        <div style={{flex: 1}}/>
                        <img className="newsListIcon" src={require('../../assets/images/eye.png')} alt=''/>
                        <div className="newsListItemOthers">{item.ClickCount}</div>
                    </div>
                </div>
                <style jsx>{`
                    .scenicListItemImg{
                        position: relative;
                        flex: 1;
                        background-position: center;
                        background-size: cover;
                        background-repeat: no-repeat;
                    }
                    .newsListSecondRow{
                        display: flex;
                        flex-direction: row;
                        align-items: center;
                        margin-top: 15px;
                    }

                    .newsListIcon{
                        width: 18px;
                    }

                    .newsListItemOthers{
                        color: #999999;
                        font-size: 14px;
                        font-weight: 300;
                        text-align: center;
                        margin-left: 3px;
                    }

                    .newsListItemLongText{
                        overflow : hidden;
                        text-overflow: ellipsis;
                        display: -webkit-box;
                        -webkit-line-clamp: 2;
                        -webkit-box-orient: vertical;
                        text-align: left;
                        margin-left: 0px;
                        line-height: 17px;
                        height: 34px;
                        margin: 5px 0 5px 0;
                    }

                    .newsListItemTextBox{
                        margin-left: 10px;
                        display: flex;
                        flex-direction: column;
                        flex: 1.5;
                        justify-content: space-between;
                        min-height: 85px;
                    }
                    .newsListItem{
                        display: flex;
                        flex-direction: row;
                        padding: 10px;
                    }

                    .newsListItemSplit{
                        border-bottom: 1px #dddddd solid;
                    }
                `}</style>
            </div>
        );
    }
    loadData()
    {
        if(this.props.isFetching)
        {
            return;
        }
        if(this.props.hasMore === false)
        {
            return;
        }

        let pageIndex = this.props.pageIndex ? (this.props.pageIndex + 1) : 1;
        this.props.dispatch(asyncGetListAction(this.props.idKey, pageIndex));
    }
    cacheScrollOffset()
    {
        if(!this.listView)
        {
            return;
        }
        let offsetY = ReactDOM.findDOMNode(this.listView).scrollTop;
        this.props.dispatch(setScrollerPositionAction(this.props.idKey, offsetY));
    }
}

NewsListView.propTypes = {
    // 列表项点击事件
    onItemClick: PropTypes.func,
};

const mapStateToProps = function(state, ownProps)
{
    let obj = state.news.listScreen.groups[ownProps.idKey];
    return {
        ...obj,
    };
};

NewsListView = connect(mapStateToProps, null, null, {withRef: true})(NewsListView);

export default NewsListView;